package com.ybkj.o2o.sales.controller.res;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Preconditions;

import com.ybkj.o2o.sales.common.DataGrid;
import com.ybkj.o2o.sales.common.transport.Error;
import com.ybkj.o2o.sales.common.transport.Result;
import com.ybkj.o2o.sales.controller.res.v4.ErrorConstantV4;
import com.ybkj.o2o.sales.controller.res.v4.ResultTransport;
import com.ybkj.o2o.sales.entity.Activity;
import com.ybkj.o2o.sales.entity.ActivityCouponRule;
import com.ybkj.o2o.sales.entity.Coupon;
import com.ybkj.o2o.sales.entity.CouponRule;
import com.ybkj.o2o.sales.manager.ActivityManager;
import com.ybkj.o2o.sales.manager.CouponManager;

import com.ybkj.o2o.sales.service.ActivityCouponRuleService;
import com.ybkj.o2o.sales.service.CouponRuleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping(value = "api/coupons")
public class CouponRes {

    @Autowired
    private CouponManager couponManager;
    @Autowired
    private ActivityManager activityManager;
    @Autowired
    private CouponRuleService couponRuleService;

    @Autowired
    private ActivityCouponRuleService activityCouponRuleService;

    /**
     * 获取一张没有绑定的线路优惠券
     *
     * @param appKey
     * @param
     * @param
     * @return
     */
    @RequestMapping(value = "findOneCoupon", method = RequestMethod.GET)
    public @ResponseBody
    ResultTransport findOneCoupon(@RequestParam(required = false, value = "appKey") String appKey,
                                  @RequestParam(required = false, value = "linesId") Long[] linesId, @RequestParam(required = false, value = "phone") String phone,
                                  @RequestParam(required = false, value = "passengerId") Long passengerId, @RequestParam(required = false, value = "activityEvent") String activityEvent) {
        if (StringUtils.isBlank(activityEvent) || null == linesId || linesId.length == 0 || StringUtils.isBlank(appKey) || StringUtils.isBlank(phone) || null == passengerId) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }
        try {
            //查询没有停止并且没过期的的活动
            List<Activity> acList = activityManager.activityList(activityEvent, linesId, appKey);
            Activity activity = null;
            if(null != acList && acList.size() > 0){
                activity = acList.get(0);
            } else {
                return ResultTransport.getErrorBy(ErrorConstantV4.ACTIVITY_IS_NONE);
            }
            List<ActivityCouponRule> acrList = activityCouponRuleService.listByActivity(activity.getId());
            if(null == acrList){
                return ResultTransport.getErrorBy(ErrorConstantV4.ACTIVITY_IS_NONE);
            }
            /** 前期硬性规定，活动类型下只能创建一个活动，一个活动只能绑定一个优惠规则 */
            ActivityCouponRule activityCouponRule = acrList.get(0);
            Long couponRuleId = activityCouponRule.getCouponRuleId();
            appKey = StringUtils.trimToEmpty(appKey);
            CouponRule couponRule = couponRuleService.findOne(couponRuleId,appKey);
            //规则定义每人限领数量（0为不限量）
            Integer eachLimit = couponRule.getEachLimit();
            //用户已经领取数量
            Integer couponTimes = couponManager.couponTimes(couponRuleId, phone, passengerId);
            Coupon coupon = null;
            ResultTransport result = null;
            //不限量或者已领数量<限领数量
            if(0 == eachLimit || couponTimes < eachLimit){
                coupon = couponManager.findOneCoupon(appKey, couponRuleId);
                if(null == coupon){
                    result = ResultTransport.getErrorBy(ErrorConstantV4.COUPON_IS_NONE);
                } else {
                    result = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
                    couponRule.setMoney(coupon.getCouponPrice());
                    coupon.setCouponRule(couponRule);
                }
            } else{
                result = ResultTransport.getErrorBy(ErrorConstantV4.COUPON_IS_EXSIT);
            }

            result.setData(coupon);
            return result;
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }
    }

    /**
     * 根据ID查询出优惠券信息.
     *
     * @param id     优惠券id
     * @param appKey 系统key
     * @return ResultTransport{code,message,data}
     */
    @RequestMapping(value = "findOne/{id}", method = RequestMethod.GET)
    public ResponseEntity<Object> getCoupon(@PathVariable("id") Long id,
                                            @RequestParam("appKey") String appKey) {

        ResponseEntity<Object> responseEntity = null;

        appKey = StringUtils.trimToEmpty(appKey);

        try {

            Coupon coupon = couponManager.findOne(id, appKey);
            if (null == coupon) {
                return new ResponseEntity<Object>(new Result<Coupon>(-1, "优惠券不存在", coupon), HttpStatus.OK);
            }

            Result<Coupon> result = new Result<Coupon>(0, "成功", coupon);

            responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);

            return responseEntity;

        } catch (Exception ex) {

            ex.printStackTrace();

            Error error = new Error(500, "内部服务器错误：" + ex.getMessage());

            responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);

            return responseEntity;
        }
    }

    /**
     * 根据code查询出优惠券信息.
     *
     * @param couponCode 优惠券编码
     * @param appKey     系统key
     * @return ResultTransport{code,message,data}
     */
    @RequestMapping(value = "findOneByCode/{couponCode}", method = RequestMethod.GET)
    public ResponseEntity<Object> getCouponByCode(@PathVariable("couponCode") String couponCode,
                                                  @RequestParam("appKey") String appKey) {

        ResponseEntity<Object> responseEntity = null;

        appKey = StringUtils.trimToEmpty(appKey);

        try {

            Coupon coupon = couponManager.findOneByCode(couponCode, appKey);
            if (null == coupon) {
                return new ResponseEntity<Object>(new Result<Coupon>(-1, "优惠券不存在", coupon), HttpStatus.OK);
            }

            Result<Coupon> result = new Result<Coupon>(0, "成功", coupon);

            responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);

            return responseEntity;

        } catch (Exception ex) {

            ex.printStackTrace();

            Error error = new Error(500, "内部服务器错误：" + ex.getMessage());

            responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);

            return responseEntity;
        }
    }


    /**
     * 生成优惠券.
     *
     * @param couponRuleId 优惠券规则id
     * @return ResultTransport{code,message,data}
     */
    @RequestMapping(value = "mass", method = RequestMethod.GET)
    public ResponseEntity<Object> mass(@RequestParam("couponRuleId") Long couponRuleId,
                                       @RequestParam("amount") Integer amount, @RequestParam("appKey") String appKey) {

        ResponseEntity<Object> responseEntity = null;
        appKey = StringUtils.trimToEmpty(appKey);
        Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
        try {

            couponManager.mass(couponRuleId, amount, appKey);

            Result<Coupon> result = new Result<Coupon>(0, "成功", null);

            responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);

            return responseEntity;
        } catch (Exception ex) {
            ex.printStackTrace();
            Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
            responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
            return responseEntity;
        }

    }
//    @RequestMapping(value = "mass", method = RequestMethod.GET)
//    public ResponseEntity<Object> mass(@RequestParam("appKey") String appKey, @RequestParam("couponRuleId") Long couponRuleId, @RequestParam("param") String param) {
//
//        ResponseEntity<Object> responseEntity = null;
//        appKey = StringUtils.trimToEmpty(appKey);
//        Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
//        CouponRule couponRule = couponRuleService.findOne(couponRuleId, appKey);
//        try {
//            JSONObject paramJson = JSON.parseObject(param);
//            List<JSONObject> jsonList = (List) paramJson.get("param");
//            for (JSONObject json : jsonList) {
//                Integer amount = Integer.parseInt(json.get("couponNumber").toString().trim());
//                Long lineId = Long.parseLong(json.get("lineId").toString().trim());
//                String lineName = json.getString("lineName");
//
//                Double couponDiscount = null;
//                BigDecimal couponPrice = null;
//                //折扣
//                if(couponRule.getType() == 0){
//                    couponDiscount = Double.parseDouble(json.getString("discount"));
//                }
//                //抵扣
//                else {
//                    couponPrice = new BigDecimal(json.get("couponPrice").toString());
//                }
//                couponManager.mass(couponRule, amount, appKey, lineId, couponPrice, couponDiscount, lineName);
//            }
//
//            Result<Coupon> result = new Result<Coupon>(0, "成功", null);
//
//            responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);
//
//            return responseEntity;
//        } catch (Exception ex) {
//            ex.printStackTrace();
//            Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
//            responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
//            return responseEntity;
//        }
//
//    }

    /**
     * 手动赠送优惠券.
     *
     * @param passengerIds    客户id
     * @param couponRuleId    活动规则id
     * @param amount          优惠券数量
     * @param passengerPhones 客户手机号
     * @param appKey          系统key
     * @return ResultTransport{code,message,data}
     */
    @RequestMapping(value = "giftcoupon", method = RequestMethod.POST)
    public ResponseEntity<Object> giftCoupon(@RequestParam("passengerIds") String passengerIds,
                                             @RequestParam("couponRuleId") String couponRuleId, @RequestParam("amount") String amount,
                                             @RequestParam("passengerPhones") String passengerPhones,
                                             @RequestParam("appKey") String appKey) {

        ResponseEntity<Object> responseEntity = null;
        appKey = StringUtils.trimToEmpty(appKey);
        Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
        try {

            couponManager.giftCoupon(passengerIds, couponRuleId, amount, passengerPhones, appKey);

            Result<Coupon> result = new Result<Coupon>(0, "成功", null);

            responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);

            return responseEntity;
        } catch (Exception ex) {
            ex.printStackTrace();
            Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
            responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
            return responseEntity;
        }

    }


    /**
     * 根据条件分页查询优惠券.
     *
     * @param ruleId 优惠券规则id
     * @param code   优惠券编码
     * @param phone  手机号
     * @param page   页数
     * @param rows   每页数量
     * @param appKey 系统key
     * @return ResultTransport{code,message,data}
     */
    @RequestMapping(value = "findCoupon", method = RequestMethod.GET)
    public ResponseEntity<Object> findCoupon(
            @RequestParam(required = true, value = "ruleId") Long ruleId, @RequestParam(required = false,
            value = "code") String code,
            @RequestParam(required = false, value = "phone") String phone, @RequestParam(
            required = false, value = "page") Integer page, @RequestParam(required = false,
            value = "rows") Integer rows, @RequestParam("appKey") String appKey) {
        ResponseEntity<Object> responseEntity = null;
        appKey = StringUtils.trimToEmpty(appKey);
        Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");

        try {
            DataGrid<Coupon> coupon = couponManager.findCoupon(ruleId, code, phone, page, rows, appKey);

            Result<DataGrid<Coupon>> result = new Result<DataGrid<Coupon>>(0, "成功", coupon);

            responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);

            return responseEntity;

        } catch (Exception ex) {
            ex.printStackTrace();
            Error error = new Error(500, "内部服务器错误：" + ex.getMessage());

            responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);

            return responseEntity;
        }

    }


    /**
     * 失效优惠券.
     *
     * @param id 优惠券id
     * @return ResultTransport{code,message,data}
     */
    @RequestMapping(value = "invalid", method = RequestMethod.PUT)
    public ResponseEntity<Object> invalid(@RequestParam("id") Long id,
                                          @RequestParam("appKey") String appKey) {
        ResponseEntity<Object> responseEntity = null;
        appKey = StringUtils.trimToEmpty(appKey);
        Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
        try {
            couponManager.invalid(id, appKey);

            Result<Coupon> result = new Result<Coupon>(0, "成功", null);

            responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);

            return responseEntity;
        } catch (Exception ex) {
            ex.printStackTrace();
            Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
            responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
            return responseEntity;
        }

    }


    /**
     * 导出.
     *
     * @param ruleId 优惠券规则id
     * @return ResultTransport{code,message,data}
     */
    @RequestMapping(value = "export", method = RequestMethod.GET)
    public ResponseEntity<Object> export(@RequestParam("ruleId") Long ruleId,
                                         @RequestParam("appKey") String appKey) {
        ResponseEntity<Object> responseEntity = null;
        appKey = StringUtils.trimToEmpty(appKey);
        Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
        try {
            List<Coupon> list = couponManager.findAll(ruleId, appKey);
            Result<List<Coupon>> result = new Result<List<Coupon>>(0, "成功", list);

            responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);

            return responseEntity;
        } catch (Exception ex) {
            ex.printStackTrace();
            Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
            responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
            return responseEntity;
        }

    }

    /**
     * 查询线路可使用优惠券(客户端)
     * @param passengerId 客户id
     * @param couponType  优惠券类型
     * @param appKey      系统key
     * @return ResultTransport{code,message,data}
     */
    @RequestMapping(value = "listValidByPassenger", method = RequestMethod.GET)
    public ResponseEntity<Object> listValidByPassenger(
            @RequestParam("passengerId") Long passengerId,
            @RequestParam(required = false, value = "couponType") String couponType,
            @RequestParam(required = false, value = "couponTypeId") Long couponTypeId,
            @RequestParam("appKey") String appKey, @RequestParam(required = false, value = "linesId") Long[] linesId) {
        ResponseEntity<Object> responseEntity = null;
        appKey = StringUtils.trimToEmpty(appKey);
        Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
        try {

            List<Coupon> list = couponManager.listValidByPassenger(passengerId, couponType, couponTypeId, appKey, linesId);
            Result<List<Coupon>> result = new Result<List<Coupon>>(0, "成功", list);

            responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);

            return responseEntity;

        } catch (Exception ex) {
            ex.printStackTrace();
            Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
            responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
            return responseEntity;
        }

    }

    /**
     * 根据客户分页查询出优惠券信息.
     *
     * @param passengerId 客户id
     * @param page        页数
     * @param rows        每页数量
     * @param appKey      系统key
     * @param status      优惠券状态
     * @return ResultTransport{code,message,data}
     */
    @RequestMapping(value = "queryByPassenger", method = RequestMethod.GET)
    public ResponseEntity<Object> queryByPassenger(
            @RequestParam(required = true, value = "passengerId") Long passengerId,
            @RequestParam(required = false, value = "status") Integer status,
            @RequestParam(required = false, value = "couponType") String couponType,
            @RequestParam(required = false, value = "page") Integer page,
            @RequestParam(required = false, value = "rows") Integer rows,
            @RequestParam(required = true, value = "appKey") String appKey) {
        ResponseEntity<Object> responseEntity = null;
        appKey = StringUtils.trimToEmpty(appKey);
        Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");

        try {

            DataGrid<Coupon> coupon = couponManager.queryByPassenger(passengerId, status, couponType, page, rows, appKey);
            Result<DataGrid<Coupon>> result = new Result<DataGrid<Coupon>>(0, "成功", coupon);

            responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);

            return responseEntity;

        } catch (Exception ex) {
            ex.printStackTrace();
            Error error = new Error(500, "内部服务器错误：" + ex.getMessage());

            responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);

            return responseEntity;
        }

    }

    /**
     * 根据id修改优惠券状态.
     *
     * @param id             优惠券id
     * @param passengerId    客户id
     * @param passengerPhone 客户手机号
     * @param status         优惠券状态
     * @param appKey         系统key
     * @return ResultTransport{code,message,data}
     */
    @RequestMapping(value = "update/{id}", method = RequestMethod.PUT)
    public ResponseEntity<Object> update(@PathVariable("id") Long id, @RequestParam(required = false,
            value = "passengerId") Long passengerId, @RequestParam(required = false,
            value = "passengerPhone") String passengerPhone, @RequestParam(required = false,
            value = "status") Integer status,
                                         @RequestParam(required = true, value = "appKey") String appKey) {

        ResponseEntity<Object> responseEntity = null;
        appKey = StringUtils.trimToEmpty(appKey);
        Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
        try {

            Coupon coupon = couponManager.findOne(id, appKey);
            if (null == coupon) {
                return new ResponseEntity<Object>(new Result<Coupon>(-1, "优惠券不存在", coupon), HttpStatus.OK);
            }

            coupon.setPassengerId(passengerId);
            coupon.setPhone(passengerPhone);
            coupon.setStatus(status);

            couponManager.update(coupon);

            Result<Coupon> result = new Result<Coupon>(0, "成功", null);

            responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);

            return responseEntity;
        } catch (Exception ex) {
            ex.printStackTrace();
            Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
            responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
            return responseEntity;
        }

    }


    /**
     * 根据客户查询出优惠券金额.
     *
     * @param passengerId 客户id
     * @param appKey      系统key
     * @return ResultTransport{code,message,data}
     */
    @RequestMapping(value = "sumMoneyByPassenger/{passengerId}", method = RequestMethod.GET)
    public ResponseEntity<Object> sumMoneyByPassenger(@PathVariable("passengerId") Long passengerId,
                                                      @RequestParam("appKey") String appKey) {

        ResponseEntity<Object> responseEntity = null;

        appKey = StringUtils.trimToEmpty(appKey);

        try {

            BigDecimal money = couponManager.sumMoneyByPassenger(passengerId, appKey);
            Result<BigDecimal> result = new Result<BigDecimal>(0, "成功", money);

            responseEntity = new ResponseEntity<Object>(result, HttpStatus.OK);

            return responseEntity;

        } catch (Exception ex) {

            ex.printStackTrace();

            Error error = new Error(500, "内部服务器错误：" + ex.getMessage());

            responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);

            return responseEntity;
        }
    }


    /**
     * 生成优惠券 导入旧数据用.
     *
     * @param passengerId  客户id
     * @param phone        客户电话
     * @param couponRuleId 优惠券规则id
     * @param status       结束时间
     * @param code         优惠券类型
     * @param runCode      打折优惠券
     * @param codeKey      抵扣优惠券
     * @param appKey       系统key
     * @return ResultTransport{code,message,data}
     */
    @RequestMapping(value = "create", method = RequestMethod.POST)
    public ResponseEntity<Object> create(
            @RequestParam(required = false, value = "passengerId") Long passengerId,
            @RequestParam(required = false, value = "phone") String phone,
            @RequestParam("couponRuleId") Long couponRuleId,
            @RequestParam("status") Integer status,
            @RequestParam("code") String code,
            @RequestParam("runCode") Long runCode,
            @RequestParam(required = false, value = "codeKey") String codeKey,
            @RequestParam("appKey") String appKey) {

        ResponseEntity<Object> responseEntity = null;
        appKey = StringUtils.trimToEmpty(appKey);
        try {

            Coupon coupon =
                    couponManager.insert(passengerId, phone, couponRuleId, status, code, runCode, codeKey,
                            appKey);

            Result<Coupon> result = new Result<Coupon>(0, "成功", coupon);

            responseEntity = new ResponseEntity<Object>(result, HttpStatus.CREATED);
            return responseEntity;
        } catch (Exception ex) {
            ex.printStackTrace();
            Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
            responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
            return responseEntity;
        }

    }

}
